<template>
  <a-modal title-align="start" :title="props.type == 'add' ? '新增分类' : '编辑分类'" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="600">
    <a-form auto-label-width ref="formRef" size="medium" :model="form">
      <a-form-item field="name" label="名称" :rules="rules.name">
        <a-input v-model="form.name" placeholder="请输入名称" allow-clear />
      </a-form-item>
      <a-form-item field="slug" label="别名" :rules="rules.slug">
        <div style="width: 100%">
          <div> <a-input v-model="form.slug" placeholder="请输入别名" allow-clear /></div>
          <div class="common-text">建议小写字母，并且只包含字母、数字和连字符。</div>
        </div>
      </a-form-item>
      <a-form-item label="父级分类">
        <a-cascader v-model="form.parent" allow-clear check-strictly :field-names="{ value: 'parentId', label: 'label' }" :options="newTreeData" placeholder="请选择" />
      </a-form-item>
      <a-form-item label="对应ERP类目" v-if="props.type == 'edit'">
        <a-cascader :options="erpCategory" v-model="form.erpCategoryId" allow-clear check-strictly :field-names="{ value: 'id', label: 'name' }" placeholder="请选择" />
      </a-form-item>
      <a-form-item label="图片">
        <a-upload class="fl" :file-list="fileList" list-type="picture-card" action="/" :limit="1" :on-before-remove="() => (fileList = [])" :on-before-upload="uploadBefore" />
      </a-form-item>
      <a-form-item label="描述">
        <a-textarea v-model="form.description" placeholder="请输入" allow-clear />
      </a-form-item>
    </a-form>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="loading" @click="submit">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { watch, ref, computed, onMounted } from 'vue'
  import { getCategoryList, batchCategory, categoryBatchCreateOrUpdateSkipNullById } from '@/api/product'
  import { OSSUpload } from '@/utils/ossUpload'
  import { findChildrenArray } from '@/utils'
  import _ from 'lodash-es'
  import { Message } from '@arco-design/web-vue'
  let props = defineProps(['modelValue', 'type', 'info', 'treeData', 'shopId'])
  let emits = defineEmits(['save', 'update:modelValue'])
  const formRef = ref()
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  let form = ref({
    name: '',
    slug: '',
    parent: '',
    description: '',
    erpCategoryId: '',
    image: {
      name: '',
      src: '',
    },
  })

  // let brandList: any = ref([])
  let loading = ref(false)
  let fileList: any = ref([])
  let newTreeData = ref([])
  let erpCategory: any = ref([])
  let rules = ref({
    name: [{ required: true, message: '请输入名字' }],
    slug: [{ required: true, message: '请输入别名' }],
    parent: [{ required: true, message: '请选择父级分类' }],
  })

  // const getBrand = async () => {
  //   const res: any = await getBrandList({ pageSize: 999999 })
  //   brandList.value = res.data?.records || []
  // }

  const setNewTreeData = (data: any) => {
    data.forEach((item: any) => {
      item.label = item.dataFromRestApi.name
      item.parentId = item.dataFromRestApi.id
      if (!item.children[0]) item.children = null
      if (item.children) {
        setNewTreeData(item.children)
      }
    })
  }

  const getCategory = async () => {
    const res: any = await getCategoryList()
    erpCategory.value = res.data || []
  }

  const uploadBefore = async (file: File) => {
    const res: any = await OSSUpload(file)
    // form.value.image.name = res.name.split('/')[res.name.split('/').length - 1]
    form.value.image.src = res.url

    let obj = {
      url: form.value.image.src,
    }
    fileList.value.push(obj)
  }

  const submit = async () => {
    const valid = await formRef.value.validate()
    if (valid) return
    let params: any = {
      param: {},
      shopId: props.shopId,
    }
    if (props.type == 'add') {
      let obj = {
        ...form.value,
        image: form.value.image,
      }
      params.param.create = [obj]
    } else {
      let obj = {
        ...form.value,
        image: form.value.image,
      }
      params.param.update = [obj]
    }

    try {
      loading.value = true
      const res: any = await batchCategory(params)
      // 选中erp类目调用方法
      if (form.value.erpCategoryId) await saveErpCategory()
      if (res) {
        Message.success(props.type == 'add' ? '新增成功。当前操作不是立即生效，请等待几分钟后刷新页面' : '编辑成功。当前操作不是立即生效，请等待几分钟后刷新页面')
        emits('save')
        showvisible.value = false
      }
    } catch (error) {}
    loading.value = false
  }

  const getProductCategoryName = () => {
    let item = findChildrenArray(erpCategory.value, form.value.erpCategoryId, 'id')
    return item?.name || ''
  }

  // 保存erp对应类目
  const saveErpCategory = async () => {
    let params = {
      createOrUpdateDocList: [
        {
          id: props.info.id,
          productCategory: {
            id: form.value.erpCategoryId,
            name: getProductCategoryName(),
          },
        },
      ],
    }
    await categoryBatchCreateOrUpdateSkipNullById(params)
  }

  const init = () => {
    let obj = {
      id: props.info.dataFromRestApi.id,
      parent: '',
      name: props.info.dataFromRestApi.name,
      slug: props.info.dataFromRestApi.slug,
      image: props.info.dataFromRestApi.image || { src: '', name: '' },
      description: props.info.dataFromRestApi.description,
      erpCategoryId: props.info?.productCategory?.id || '',
    }
    let item = findChildrenArray(newTreeData.value, obj.id, 'parentId')
    item.dataFromRestApi.parent ? (obj.parent = item.dataFromRestApi.parent) : ''

    form.value = obj

    if (obj?.image?.src) fileList.value.push({ url: obj?.image?.src || '' })
  }

  watch(
    () => props.treeData,
    (val) => {
      newTreeData.value = _.cloneDeep(val)
      setNewTreeData(newTreeData.value)
    },
    {
      deep: true,
      immediate: true,
    }
  )

  onMounted(() => {
    getCategory()
    props.type != 'add' ? init() : ''
  })
</script>

<style lang="less" scoped></style>
